<template>
  <div class="note-list-container">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <el-button class="back-btn" circle @click="goHome">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h1>💌 爱的小纸条</h1>
      <el-button class="write-btn" circle @click="showSendDialog">
        <el-icon><EditPen /></el-icon>
      </el-button>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-bar">
      <div class="stat-item">
        <span class="stat-label">收到的纸条</span>
        <span class="stat-value">{{ total }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">未读纸条</span>
        <span class="stat-value unread">{{ unreadCount }}</span>
      </div>
    </div>

    <!-- 操作按钮区 -->
    <div class="action-bar" v-if="noteList.length > 0">
      <!-- 批量选择模式下的按钮 -->
      <template v-if="batchMode">
        <el-button
          class="action-btn cancel-btn"
          @click="cancelBatchMode"
        >
          ❌ 取消
        </el-button>
        <el-button
          class="action-btn confirm-btn"
          type="success"
          @click="confirmBatchDelete"
          :disabled="selectedNotes.length === 0"
        >
          ✅ 确认删除 ({{ selectedNotes.length }})
        </el-button>
      </template>

      <!-- 正常模式下的按钮 -->
      <template v-else>
        <el-button
          class="action-btn"
          type="danger"
          plain
          @click="enterBatchMode"
        >
          🗑️ 批量删除
        </el-button>
        <el-button
          class="action-btn"
          type="warning"
          plain
          @click="handleDeleteAll"
        >
          🧹 一键清空
        </el-button>
      </template>
    </div>

    <div class="note-list" v-loading="loading">
      <div v-if="noteList.length === 0" class="empty-state">
        <el-empty description="还没有收到小纸条哦" />
      </div>

      <transition-group name="note-list" tag="div" class="note-items">
        <div
          v-for="note in noteList"
          :key="note.id"
          class="note-card"
          :class="{
            'unread': !note.isRead,
            'selected': isSelected(note.id),
            'batch-mode': batchMode
          }"
          @click="handleCardClick(note)"
        >
          <!-- 批量选择模式下显示复选框 -->
          <div v-if="batchMode" class="note-checkbox" @click.stop="toggleSelect(note.id)">
            <el-checkbox
              :model-value="isSelected(note.id)"
              @change="toggleSelect(note.id)"
              size="large"
            />
          </div>

          <div class="note-envelope" :class="{ 'opened': note.isRead }">
            <div class="envelope-flap"></div>
            <div class="envelope-body">
              <div class="note-content">
                <p class="content-text">{{ note.content }}</p>
              </div>
            </div>
          </div>

          <div class="note-footer">
            <span class="note-time">{{ formatTime(note.createdAt) }}</span>
            <div class="note-actions" v-if="!batchMode">
              <el-button
                v-if="!note.isRead"
                type="primary"
                size="small"
                @click.stop="markAsRead(note.id)"
              >
                标记已读
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click.stop="handleDelete(note.id)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </transition-group>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="loadNoteList"
        />
      </div>
    </div>

    <!-- 发送小纸条对话框 -->
    <el-dialog
      v-model="sendDialogVisible"
      title="💌 写一张小纸条给TA"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="sendFormRef" :model="sendForm" :rules="sendRules">
        <el-form-item prop="content">
          <el-input
            v-model="sendForm.content"
            type="textarea"
            :rows="6"
            placeholder="写下你想对TA说的话..."
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <div class="quick-templates">
          <p class="template-title">💡 快速模板：</p>
          <div class="template-buttons">
            <el-button size="small" @click="useTemplate('今天想你了 ❤️')">今天想你了 ❤️</el-button>
            <el-button size="small" @click="useTemplate('爱你哟 😘')">爱你哟 😘</el-button>
            <el-button size="small" @click="useTemplate('晚安，做个好梦 🌙')">晚安 🌙</el-button>
            <el-button size="small" @click="useTemplate('早安，今天也要开心哦 ☀️')">早安 ☀️</el-button>
            <el-button size="small" @click="useTemplate('辛苦了，要好好休息 💪')">辛苦了 💪</el-button>
          </div>
        </div>
      </el-form>

      <template #footer>
        <el-button @click="sendDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSend" :loading="sending">
          💌 发送
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, EditPen } from '@element-plus/icons-vue'
import {
  getLoveNoteList,
  sendLoveNote,
  markLoveNoteAsRead,
  deleteLoveNote,
  getUnreadLoveNoteCount,
  batchDeleteLoveNotes,
  deleteAllLoveNotes
} from '@/api'
import websocketManager from '@/utils/websocket'

const router = useRouter()

const loading = ref(false)
const noteList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const unreadCount = ref(0)
const selectedNotes = ref([]) // 选中的小纸条ID列表
const batchMode = ref(false) // 批量选择模式

const sendDialogVisible = ref(false)
const sendFormRef = ref(null)
const sending = ref(false)

const sendForm = reactive({
  content: ''
})

const sendRules = {
  content: [
    { required: true, message: '请输入小纸条内容', trigger: 'blur' },
    { min: 1, max: 200, message: '内容长度在 1 到 200 个字符', trigger: 'blur' }
  ]
}

// 加载小纸条列表
const loadNoteList = async () => {
  loading.value = true
  try {
    const res = await getLoveNoteList({
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    
    if (res.code === 200) {
      noteList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '加载小纸条列表失败')
    }
  } catch (error) {
    console.error('加载小纸条列表失败：', error)
    ElMessage.error('加载小纸条列表失败')
  } finally {
    loading.value = false
  }
}

// 加载未读数量
const loadUnreadCount = async () => {
  try {
    const res = await getUnreadLoveNoteCount()
    if (res.code === 200) {
      unreadCount.value = res.data || 0
    }
  } catch (error) {
    console.error('加载未读数量失败：', error)
  }
}

// 显示发送对话框
const showSendDialog = () => {
  sendForm.content = ''
  sendDialogVisible.value = true
}

// 使用模板
const useTemplate = (template) => {
  sendForm.content = template
}

// 提交发送
const submitSend = async () => {
  if (!sendFormRef.value) return
  
  await sendFormRef.value.validate(async (valid) => {
    if (valid) {
      sending.value = true
      try {
        const res = await sendLoveNote({
          content: sendForm.content
        })
        
        if (res.code === 200) {
          ElMessage.success('小纸条发送成功！TA会收到通知哦 💕')
          sendDialogVisible.value = false
          sendForm.content = ''
        } else {
          ElMessage.error(res.msg || '发送小纸条失败')
        }
      } catch (error) {
        console.error('发送小纸条失败：', error)
        ElMessage.error('发送小纸条失败')
      } finally {
        sending.value = false
      }
    }
  })
}

// 点击卡片
const handleCardClick = (note) => {
  // 批量选择模式：点击卡片切换选中状态
  if (batchMode.value) {
    toggleSelect(note.id)
  } else {
    // 正常模式：点击未读纸条标记为已读
    if (!note.isRead) {
      markAsRead(note.id)
    }
  }
}

// 标记为已读
const markAsRead = async (id) => {
  try {
    const res = await markLoveNoteAsRead(id)
    if (res.code === 200) {
      ElMessage.success('已标记为已读')
      loadNoteList()
      loadUnreadCount()
    } else {
      ElMessage.error(res.msg || '标记失败')
    }
  } catch (error) {
    console.error('标记失败：', error)
    ElMessage.error('标记失败')
  }
}

// 删除小纸条
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这张小纸条吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteLoveNote(id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadNoteList()
      loadUnreadCount()
      // 清空选中状态
      selectedNotes.value = []
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换选中状态
const toggleSelect = (id) => {
  const index = selectedNotes.value.indexOf(id)
  if (index > -1) {
    selectedNotes.value.splice(index, 1)
  } else {
    selectedNotes.value.push(id)
  }
}

// 判断是否选中
const isSelected = (id) => {
  return selectedNotes.value.includes(id)
}

// 进入批量选择模式
const enterBatchMode = () => {
  batchMode.value = true
  selectedNotes.value = []
  ElMessage.info('请点击小纸条进行选择')
}

// 取消批量选择模式
const cancelBatchMode = () => {
  batchMode.value = false
  selectedNotes.value = []
}

// 确认批量删除
const confirmBatchDelete = async () => {
  if (selectedNotes.value.length === 0) {
    ElMessage.warning('请先选择要删除的小纸条')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedNotes.value.length} 张小纸条吗？`,
      '批量删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    const res = await batchDeleteLoveNotes(selectedNotes.value)
    if (res.code === 200) {
      ElMessage.success(`成功删除 ${selectedNotes.value.length} 张小纸条`)
      selectedNotes.value = []
      batchMode.value = false
      loadNoteList()
      loadUnreadCount()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败：', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 一键删除所有
const handleDeleteAll = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除所有小纸条吗？此操作不可恢复！`,
      '一键清空',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
    )

    const res = await deleteAllLoveNotes()
    if (res.code === 200) {
      ElMessage.success('已清空所有小纸条')
      selectedNotes.value = []
      loadNoteList()
      loadUnreadCount()
    } else {
      ElMessage.error(res.msg || '清空失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败：', error)
      ElMessage.error('清空失败')
    }
  }
}

// 返回主页
const goHome = () => {
  router.push('/home')
}

// 格式化时间
const formatTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const now = new Date()
  const diff = now - date
  
  // 1分钟内
  if (diff < 60000) {
    return '刚刚'
  }
  // 1小时内
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  // 今天
  if (date.toDateString() === now.toDateString()) {
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `今天 ${hour}:${minute}`
  }
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `昨天 ${hour}:${minute}`
  }
  // 其他
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${month}-${day}`
}

// WebSocket 消息处理器
const handleWebSocketMessage = (notification) => {
  console.log('小纸条页面收到 WebSocket 消息', notification)

  // 如果是小纸条通知，刷新列表
  if (notification.type === 'NOTE_RECEIVED') {
    ElMessage({
      message: '💌 收到新的小纸条！',
      type: 'success',
      duration: 3000
    })

    // 刷新小纸条列表和未读数量
    loadNoteList()
    loadUnreadCount()
  }
}

onMounted(() => {
  loadNoteList()
  loadUnreadCount()

  // 添加 WebSocket 消息监听
  websocketManager.onMessage(handleWebSocketMessage)
})

onUnmounted(() => {
  // 移除 WebSocket 消息监听
  websocketManager.offMessage(handleWebSocketMessage)
})
</script>

<style scoped>
.note-list-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding-bottom: 20px;
}

/* 顶部标题栏 */
.page-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: linear-gradient(135deg, #ff85c0 0%, #ff69b4 100%);
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.2);
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
  flex: 1;
  text-align: center;
}

.back-btn,
.write-btn {
  background: rgba(255, 255, 255, 0.3);
  border: none;
  color: white;
  width: 36px;
  height: 36px;
}

.back-btn:hover,
.write-btn:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 统计卡片 */
.stats-bar {
  display: flex;
  gap: 12px;
  padding: 16px;
}

.stat-item {
  flex: 1;
  background: white;
  border-radius: 16px;
  padding: 16px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.1);
}

.stat-label {
  display: block;
  font-size: 13px;
  color: #999;
  margin-bottom: 8px;
}

.stat-value {
  display: block;
  font-size: 28px;
  font-weight: bold;
  color: #ff69b4;
}

.stat-value.unread {
  color: #f56c6c;
}

/* 操作按钮区 */
.action-bar {
  display: flex;
  gap: 8px;
  padding: 0 16px 16px;
  flex-wrap: wrap;
}

.action-btn {
  flex: 1;
  min-width: 0;
  height: 40px;
  font-size: 14px;
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-btn:active {
  transform: scale(0.95);
}

/* 批量模式按钮 */
.cancel-btn {
  flex: 1;
  background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
  border-color: #d9d9d9;
  color: #666;
}

.confirm-btn {
  flex: 2;
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  border: none;
  color: white;
}

.confirm-btn:hover {
  background: linear-gradient(135deg, #73d13d 0%, #52c41a 100%);
}

.confirm-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 小纸条列表 */
.note-list {
  min-height: 400px;
  padding: 0 16px;
}

.empty-state {
  padding: 60px 0;
}

.note-items {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.note-card {
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
}

.note-card:hover {
  transform: translateY(-4px);
}

.note-card.unread .note-envelope {
  box-shadow: 0 4px 20px rgba(245, 108, 108, 0.3);
}

/* 批量选择模式 */
.note-card.batch-mode {
  cursor: pointer;
}

.note-card.batch-mode:hover {
  transform: scale(1.02);
}

.note-card.batch-mode .note-envelope {
  border: 2px dashed #ffb3d9;
  transition: all 0.3s ease;
}

.note-card.batch-mode:hover .note-envelope {
  border-color: #ff69b4;
  background: linear-gradient(135deg, #fff 0%, #fff5fb 100%);
}

/* 选中状态 */
.note-card.selected {
  transform: scale(0.98);
}

.note-card.selected .note-envelope {
  border: 2px solid #ff69b4 !important;
  box-shadow: 0 4px 20px rgba(255, 105, 180, 0.4);
  background: linear-gradient(135deg, #fff5fb 0%, #ffeef8 100%) !important;
}

/* 复选框样式 */
.note-checkbox {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  background: white;
  border-radius: 50%;
  padding: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  animation: checkboxFadeIn 0.3s ease;
}

@keyframes checkboxFadeIn {
  from {
    opacity: 0;
    transform: scale(0.5);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.note-checkbox:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.3);
}

.note-card.selected .note-checkbox {
  background: linear-gradient(135deg, #ff69b4 0%, #ff85c0 100%);
  animation: checkboxPulse 0.3s ease;
}

@keyframes checkboxPulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.note-card.selected .note-checkbox :deep(.el-checkbox__inner) {
  background-color: white;
  border-color: white;
}

.note-card.selected .note-checkbox :deep(.el-checkbox__inner::after) {
  border-color: #ff69b4;
}

/* 批量模式提示 */
.note-card.batch-mode .note-envelope::before {
  content: '点击选择';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 14px;
  color: #ffb3d9;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.note-card.batch-mode:hover .note-envelope::before {
  opacity: 0.5;
}

.note-envelope {
  position: relative;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(255, 105, 180, 0.1);
  min-height: 150px;
  transition: all 0.3s ease;
}

.note-envelope.opened {
  background: linear-gradient(135deg, #fff 0%, #ffeef8 100%);
}

.envelope-flap {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 40px;
  background: linear-gradient(135deg, #ff69b4 0%, #ff85c0 100%);
  border-radius: 12px 12px 0 0;
  clip-path: polygon(0 0, 50% 100%, 100% 0);
}

.envelope-body {
  padding-top: 20px;
}

.note-content {
  min-height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content-text {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  text-align: center;
  margin: 0;
  word-wrap: break-word;
}

.note-footer {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #ffe5f1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.note-time {
  font-size: 12px;
  color: #999;
}

.note-actions {
  display: flex;
  gap: 8px;
}

.pagination {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.quick-templates {
  margin-top: 20px;
  padding: 15px;
  background: #ffeef8;
  border-radius: 8px;
}

.template-title {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #666;
}

.template-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 列表动画 */
.note-list-enter-active,
.note-list-leave-active {
  transition: all 0.5s ease;
}

.note-list-enter-from {
  opacity: 0;
  transform: translateY(-30px);
}

.note-list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header h1 {
    font-size: 18px;
  }

  .stat-value {
    font-size: 24px;
  }

  .stat-label {
    font-size: 12px;
  }

  .action-bar {
    gap: 6px;
  }

  .action-btn {
    font-size: 13px;
    height: 36px;
    padding: 0 12px;
  }

  .note-items {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .note-card {
    margin: 0;
  }

  .note-envelope {
    padding: 16px;
    min-height: 120px;
  }

  .content-text {
    font-size: 15px;
  }

  .note-actions .el-button {
    font-size: 12px;
    padding: 4px 10px;
  }

  /* 分页器移动端优化 */
  :deep(.el-pagination .el-pager li) {
    min-width: 28px;
    height: 28px;
    line-height: 28px;
    font-size: 13px;
  }

  :deep(.el-pagination button) {
    padding: 0 8px;
    font-size: 13px;
  }
}

/* 平板及以上 */
@media (min-width: 768px) {
  .note-list-container {
    padding-bottom: 40px;
  }

  .note-list {
    max-width: 900px;
    margin: 0 auto;
    padding: 0 24px;
  }

  .stats-bar {
    max-width: 900px;
    margin: 0 auto;
    padding: 24px;
  }

  .action-bar {
    max-width: 900px;
    margin: 0 auto 24px;
    padding: 0 24px;
  }

  .action-btn {
    max-width: 200px;
  }

  .note-items {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
  }
}
</style>

